<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\Picture;
use App\Models\Reply;
use App\Models\TopicCategory;
use App\Models\Topic;
use App\Models\ArticleCategory;
use Illuminate\Support\Facades\Request;
use App\Jobs\ProcessTopicView;
use App\Jobs\ProcessTopicReply;
use App\Jobs\ProcessMessage;
use App\Http\Resources\ReplyResource;
use App\Http\Resources\TopicResource;
use App\Http\Requests\Publish;
use App\Http\Requests\Reply as RequestsReply;
use Illuminate\Http\Request as HttpRequest;

class IndexController extends Controller
{

    protected $topicSelect = ['id', 'title', 'user_id', 'category_id', 'reply_count', 'view_count', 'is_top', 'order', 'created_at'];

    protected $topicMdl;

    public function __construct(Topic $topic)
    {
        $this->topicMdl = $topic;
    }

    /**
     * 首页
     * User: 920078259@qq.com
     * @param ArticleCategory $articleCategory
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(ArticleCategory $articleCategory)
    {

        $category = Request::input('category');
        $where = $category ? ['category_id' => $category] : [];
        return $this->json([
            'topic' => $this->topicMdl->getList($where, ['user', 'category'], $this->topicMdl->select, 1, 6),
            'article' => $articleCategory->getRow(1, 'article'),
            'hot' => $this->topicMdl->weekHot()
        ]);
    }

    /**
     * 分类|导航
     * User: 920078259@qq.com
     * @param TopicCategory $topicCategory
     * @return \Illuminate\Http\JsonResponse
     */
    public function category(TopicCategory $topicCategory)
    {
        // nav 为首页导航，不然就是发布的分类
        $type = Request::input('type', 'nav');
        if ($type == 'nav') {
            $list = $topicCategory->getNavs();
        } else {
            $list = $topicCategory->getPublishCate();
        }

        return $this->json($list);
    }

    /**
     * 获取话题分页
     * User: 920078259@qq.com
     * @param $cate
     * @return \Illuminate\Http\JsonResponse
     */
    public function topic($cate)
    {

        $order = Request::input('order', ''); // 排序（最新、最热、评论最多）
        $page = Request::input('page');
        $perPage = Request::input('per_page');

        $where = $cate ? ['category_id' => $cate] : [];
        $order = $this->topicMdl->getOrder($order);
        $data = $this->topicMdl->getPaginate(
            $where,
            ['user', 'category'],
            $this->topicMdl->select,
            $page,
            $perPage,
            $order
        );

        return $this->json($data);
    }

    /**
     * 详情页
     * User: 920078259@qq.com
     * @param $id
     * @param TopicResource $topicResource
     * @param ReplyResource $replyResource
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id, TopicResource $topicResource, ReplyResource $replyResource)
    {
        // 更新查看次数
        ProcessTopicView::dispatch($id);
        return $this->json([
            'detail' => $topicResource->format($id),
            'reply' => $replyResource->format($id),
            'hot' => $this->topicMdl->weekHot()
        ]);
    }

    /**
     * 文章详情
     * User: 920078259@qq.com
     * @param $id
     * @param Article $article
     * @param ArticleCategory $articleCategory
     * @return \Illuminate\Http\JsonResponse
     */
    public function article($id, Article $article, ArticleCategory $articleCategory)
    {

        $data = $article->find($id);
        if ($data) {
            return $this->json([
                'detail' => $data,
                'article' => $articleCategory->getRow(1, 'article')
            ]);
        }

        return $this->json([], '参数错误', 400);
    }

    /**
     * 广告位
     * User: 920078259@qq.com
     * @param $id int 分类id
     * @param Picture $picture
     * @return \Illuminate\Http\JsonResponse
     */
    public function advertising(int $id, Picture $picture)
    {
        $data = $picture->getList(['cate_id' => 1]);

        return $this->json($data);
    }

    /**
     * 评论|回复评论
     * User: 920078259@qq.com
     * @param $id
     * @param RequestsReply $reply
     * @return \Illuminate\Http\JsonResponse
     */
    public function reply($id, RequestsReply $reply)
    {

        $validata = $reply->validated();

        $data = [
            'topic_id' => $id,
            'user_id' => $validata['user_id'],
            'to_user' => $validata['to_user'],
            'content' => $validata['content']
        ];

        // 录入评论
        ProcessTopicReply::dispatch($data);

        // 通知消息（如果自己给自己评论就不用通知了）
        if ($validata['user_id'] != $validata['to_user']) {
            ProcessMessage::dispatch($data);
        }

        return $this->json();
    }

    /**
     * 采纳评论
     * User: 920078259@qq.com
     * @param $replyId
     * @param Reply $reply
     * @param Topic $topic
     * @return \Illuminate\Http\JsonResponse
     */
    public function adopt($replyId, Reply $reply, Topic $topic)
    {
        $userId = Request::header('UserId');
        $replyInfo = $reply->find($replyId);
        $topic_user_id = $topic->where('id', $replyInfo['topic_id'])->value('user_id');
        // 不是楼主自己采纳的
        if ($topic_user_id != $userId) {
            return $this->json([], '非法操作', 400);
        }
        $is_adopt = $reply->where(['topic_id' => $replyInfo['topic_id'], 'is_adopt' => 1])->count();
        if ($is_adopt) {
            return $this->json([], '最多只能采纳一条评论，你已经采纳过一条了', 400);
        }
        $replyInfo->is_adopt = 1;
        $replyInfo->save();

        return $this->json();
    }

    /**
     * 发布话题
     * User: 920078259@qq.com
     * @param Publish $request
     * @param Topic $topic
     * @return \Illuminate\Http\JsonResponse
     */
    public function publish(Publish $request, Topic $topic)
    {

        // 验证数据
        $validata = $request->validated();
        $data = [
            'title' => $validata['title'],
            'body' => $validata['body'],
            'category_id' => $validata['category_id'],
            'user_id'   => Request::header('UserId'),
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        $id = $topic->addData($data);

        return $this->json($id);
    }

    /**
     * 编辑话题
     * User: 920078259@qq.com
     * @param Publish $request
     * @param Topic $topic
     * @return \Illuminate\Http\JsonResponse
     */
    public function editPublish($id, Publish $request, Topic $topic)
    {

        // 验证数据
        $validata = $request->validated();
        $topicInfo = $topic->find($id);
        $userId = Request::header('UserId');
        if ($topicInfo['user_id'] != $userId) {
            return $this->json([], '只能编辑自己发布的作品');
        }

        $topicInfo->title = $validata['title'];
        $topicInfo->body = $validata['body'];
        $topicInfo->category_id = $validata['category_id'];
        $topicInfo->save();

        return $this->json($id);
    }

    /**
     * 上传图片
     * User: 920078259@qq.com
     * @param HttpRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploads(HttpRequest $request)
    {

        $result = $request->file('file')->store('/public/public/tinymce/images/' . date('Ym'));

        return $this->json(config('filesystems.disks.public.url') . substr($result, 6));
    }


}
